package com.greateffect.littlebud.lib.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;

import com.greateffect.littlebud.lib.R;
import com.zcs.autolayout.utils.AutoUtils;

public class RoundImageView extends AppCompatImageView {

    private int mRadius; // px
    private Path mRoundedRectPath;
    private RectF mRectF;

    public RoundImageView(Context context) {
        this(context, null);
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        // 读取配置
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView);
        mRadius = array.getDimensionPixelOffset(R.styleable.RoundImageView_riv_radius, 0);
        if (mRadius > 0) {
            mRadius = AutoUtils.getPercentWidthSize(mRadius);
        }
        array.recycle();
        init();
    }

    private void init() {
        mRoundedRectPath = new Path();
        mRectF = new RectF();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mRectF.set(0.0f, 0.0f, getWidth(), getHeight());
        mRoundedRectPath.addRoundRect(mRectF, mRadius, mRadius, Path.Direction.CW);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.clipPath(mRoundedRectPath);
        super.onDraw(canvas);
    }
}